/*
 * @Date: 2024-11-11 09:25:23
 * @Author: LiSong
 * @LastEditors: LiSong
 * @LastEditTime: 2024-11-19 11:17:22
 * @Description: 专项评审申报操作方法
 */
import XEUtils from 'xe-utils';
import HandlerUtils from '@/handler/utils/HandlerUtils.js'
import { defAxios as request } from '@/utils/http';

import { reactive } from "vue"

import { RkConfirmBox } from '@/components/message-box/index.js'
import { openXmsbDialog } from '@hd/base/service/HdCallCompService.js'
import { openOperationLogs } from '@/plugins/call-comp/CallCompService.js'

import WfTask from '@/handler/pojo/WfTask.js'

function reserveProjHandleTask(params) {
  return request({
      url: '/proResApply/handleTask',
      method: 'post',
      data: params,
  });
}

const useLayoutHandler = (params) => {

  // 参数
  const { routeQuery, userInfo, tableSearch } = params

  // 基本信息
  const baseData = reactive({
    // 选中项目ID
    proId: '',
    // 选中区划编码
    adCode: userInfo.adBjCode,
    // 单位ID
    agId: '',
    // 选中单位编码
    agCode: '',
    // 单位名称
    agName: '',
    // 上级单位Id
    agParentId: '',
    // 工作流
    processKey: routeQuery.processKey,
  })

  /**
   * 按钮组右侧按钮点击事件
   */
  const btnGroupRightClick = async ({ rightItem, extParams }) => {
    const { agData, checkRows } = extParams
    const btnType = rightItem.value
    if (btnType === 'add') {
      const existParent = (agData.parentId == '0')
      const addInfo = {
        ...XEUtils.clone(baseData, true),
        agId: agData.id,
        agCode: agData.code,
        agName: agData.name,
        agParentId: existParent ? agData.parentName : '',
        agParentName: existParent ? agData.parentId : '',
      }
      handleOpenXmsbDialog('add', addInfo)
    } else if (btnType === 'edit') {
      const row = checkRows[0]
      const editInfo = {
        ...XEUtils.clone(baseData, true),
        agId: row.agId,
        agCode: row.agCode,
        agName: row.agName,
        adCode: row.adCode,
        adName: row.adName,
        proId: row.proId,
        applyId: row.applyId,
      }
      handleOpenXmsbDialog('edit', editInfo)
    } else if (btnType === 'send') {
      const tempRow = checkRows.find(item => item.isTemp === 1)
      if (tempRow) {
        HandlerUtils.warningMsgTip('选中数据在暂存区，请完善信息保存后进行送审！')
        return
      }
      HandlerUtils.openLoadService(rightItem.label)
      const reqParams = coverOperateParams(checkRows, WfTask.SEND.value)
      const result = await reserveProjHandleTask(reqParams)
      const { data, code, msg } = result
      if (code === 200) {
        if (data && data['isAuditPass'] === '0') {
          HandlerUtils.warningMsgTip('存在需整改的项目单位，禁止送审！')
          return
        }
        HandlerUtils.successMsgTip(rightItem.label)
        tableSearch()
      } else {
        HandlerUtils.failedMsgTip(result.msg, true)
      }
      HandlerUtils.closeLoadService()
    } else if (btnType === 'cancel') {
      HandlerUtils.openLoadService(rightItem.label)
      const reqParams = coverOperateParams(checkRows, WfTask.CANCEL.value)
      const result = await reserveProjHandleTask(reqParams)
      if (result.code === 200) {
        HandlerUtils.successMsgTip(rightItem.label)
        tableSearch()
      } else {
        HandlerUtils.failedMsgTip(result.msg, true)
      }
      HandlerUtils.closeLoadService()
    } else if (btnType === 'delete') {
      RkConfirmBox({
        title: '提示',
        content: `您确定要${rightItem.label}吗？`,
        onSubmit: async function () {
          HandlerUtils.openLoadService(rightItem.label)
          const reqParams = coverOperateParams(checkRows, WfTask.CANCEL.value)
          const result = await request({
            url: '/proResApply/deleteReserveProject',
            method: 'POST',
            data: {
              proIds: reqParams.proIds, applyIds: reqParams.applyIds
            },
          })
          if (result.code === 200) {
            HandlerUtils.successMsgTip(rightItem.label)
            tableSearch()
          } else {
            HandlerUtils.failedMsgTip(result.msg, true)
          }
          HandlerUtils.closeLoadService()
        }
      })
    } else if (btnType === 'log') {
      openOperationLogs(checkRows)
    }
  }


  /**
   * 打开项目申报弹窗
   * 
   * @param type 类型
   * @param info 信息
   */
  const handleOpenXmsbDialog = (type, info) => {
    openXmsbDialog({
      type: type,
      title: '评审项目申报',
      formCode: routeQuery.tbFormCode,
      compType: 'special',
      extParams: { ...info, formType: type },
      onConfirm: () => {
        tableSearch()
      }
    })
  }

  /**
   * 封装操作数据
   * 
   * @param checkRows 选中的数据
   * @param wfType 工作流状态
   */
  const coverOperateParams = (checkRows, wfType) => {
    let proIds = []
    let taskIds = []
    let applyIds = []
    for (const row of checkRows) {
      proIds.push(row.proId)
      taskIds.push(row.taskId)
      applyIds.push(row.applyId)
    }
    return {
      // 流程节点
      nodeId: routeQuery.nodeId,
      proIds: proIds.join(','),
      taskIds: taskIds.join(','),
      applyIds: applyIds.join(','),
      taskType: wfType || '',
      adCode: baseData.adCode,
      agCode: '',
      processKey: baseData.processKey,
      bondTypeCode: 2,
    }
  }

  return {
    baseData,
    buttonClick: null,
    btnGroupRightClick
  }

}

export default useLayoutHandler
